﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Web;

using System.Data;
using System.Data.SqlClient;

/// <summary>
/// Summary description for API_Auth
/// </summary>
public class API_Auth
{
	public API_Auth()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    public static int Check(string uid, string sign_key, string sign, out string office)
    {
        DataTable bufTab;
        SqlCommand cmd = new SqlCommand();
        SqlParameter para;
        DataTable dt = new DataTable();
        string pwd;
        int ret_code=0;
        office = "";
        
        if (uid.Length < 1 || uid.Length > 20 || sign.Length > 50 || sign_key.Length>300)
            return -1001;

        office = "";
        bufTab = (DataTable)MyCache.GetCache("uid:" + uid);
        if (bufTab == null)
        {
            try
            {
                cmd.CommandText = "sali_user0_get_pwd_hash";
                para = cmd.Parameters.AddWithValue("@uid", uid);
                ret_code = TinyDAL.Exec(ref cmd, ref dt);
            }
            catch (Exception ex)
            {
                return -1002;
            }
            if (dt.Rows.Count != 1)
                return -1003;
            MyCache.SetCache("uid:" + uid, dt, 307, 0);//用户密码结果集缓存307秒
            pwd = dt.Rows[0]["password"].ToString();
            office = dt.Rows[0]["office"].ToString();
        }
        else
        {
            pwd = bufTab.Rows[0]["password"].ToString();
            office = bufTab.Rows[0]["office"].ToString();
        }

        string inbuf = sign_key + "|" + pwd;
        string outbuf = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(inbuf, "MD5");
        if (outbuf != sign)
            return -1004;

        return 0;
    }
}